home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / IOBuffer.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  2.3 KB  |  68 lines

  1. # IOBuffer.py Copyright (c) 2006 Participatory Culture Foundation
  2. #
  3. # Implements a file-like object similar to stringIO, except that it
  4. # provides the data as a continuous read-only stream instead of a
  5. # string. Made for use in a multithreaded environment where a producer
  6. # writes and a consumer reads.  There's currently no limit on the
  7. # buffer size, so this could consume lots of memory if the write
  8. # function gets ahead of the read
  9. #
  10. # Only supports one consumer.
  11. #
  12. # read() blocks until there's some data left to return
  13.  
  14. from Queue import Queue
  15.  
  16. class IOBuffer:
  17.     def __init__(self):
  18.         # Force self.buf to be a string or unicode
  19.         self.bufs = Queue()
  20.         self.curBuf = ''
  21.         self.pos = 0
  22.         self.softspace = 0
  23.         
  24.     def read(self, size = None):
  25.         remaining = len(self.curBuf) - self.pos
  26.         if size is None:  # Grab everything
  27.             output = []
  28.             if remaining > 0:
  29.                 output.append(self.curBuf[self.pos:])
  30.                 self.pos = 0
  31.                 self.curBuf = ''
  32.             data = self.bufs.get()
  33.             while len(data) > 0:
  34.                 output.append(data)
  35.                 data = self.bufs.get()
  36.             return ''.join(output)
  37.         
  38.         elif remaining > 0: # There's leftover data outside the queue
  39.                             # and a size limit
  40.  
  41.             if remaining <= size: # The leftover data fits in size bytes
  42.                 ret = self.curBuf[self.pos:]
  43.                 self.pos = len(self.curBuf)
  44.                 return ret
  45.             else:                 # The leftover data won't fit in size bytes
  46.                 ret = self.curBuf[self.pos:self.pos+size]
  47.                 self.pos += size
  48.                 return ret
  49.         else:
  50.             newBuf = self.bufs.get()
  51.             if len(newBuf) <= size: # Send the string through now
  52.                 return newBuf
  53.             else:
  54.                 self.pos = size
  55.                 self.curBuf = newBuf
  56.                 return newBuf[0:size]
  57.  
  58.     # FIXME: deprecated --used to allow an IOBuffer as the output of a template
  59.     def getOutput(self):
  60.         return self.read()
  61.  
  62.     def write(self, string):
  63.         if len(string) > 0:
  64.             self.bufs.put(string)
  65.  
  66.     def close(self):
  67.         self.bufs.put('')
  68.